<template>
    <div class="inventory-alert-container">
        <!-- 搜索筛选区域 -->
        <div class="search-section">
            <p class="section-title">数据筛选</p>
            <el-form :inline="true" :model="data" class="search-form">
                <el-form-item label="货品:" class="form-item">
                    <el-input v-model="data.Name" placeholder="请输入货品名称/编号" clearable class="custom-input" />
                </el-form-item>

                <el-form-item label="货品类型:" class="form-item">
                    <el-tree-select
                        v-model="data.Type"
                        :data="categoryTreeList"
                        placeholder="请选择"
                        clearable
                        check-strictly
                        :props="{
                        children: 'children',
                        label: 'category_Name',
                        value: 'id',
                        }"
                        style="width: 200px"
                    />
                </el-form-item>

                <el-form-item label="上下限:" class="form-item">
                    <el-select v-model="data.UpUnder" placeholder="请选择" clearable class="custom-select"
                        style="width: 100px;">
                        <el-option label="低于下限" value="低于下限" />
                        <el-option label="高于上限" value="高于上限" />
                    </el-select>
                </el-form-item>

                <el-form-item label="当前库存:" class="form-item">
                    <div class="range-inputs">
                        <el-input v-model="data.Up" placeholder="请输入" clearable class="custom-input range-input" />
                        <span class="range-separator">~</span>
                        <el-input v-model="data.Under" placeholder="请输入" clearable class="custom-input range-input" />
                    </div>
                </el-form-item>

                <el-form-item class="form-item">
                    <div class="button-group">
                        <el-button @click="resetForm" class="reset-btn">
                            重置
                        </el-button>
                        <el-button type="primary" @click="GetInventory" class="search-btn">
                            查询
                        </el-button>
                    </div>
                </el-form-item>
            </el-form>
        </div>

        <!-- 操作按钮区域 -->
        <div class="action-section">
            <el-button @click="GetInventory" class="refresh-btn">
                刷新
            </el-button>
            <el-button type="primary" @click="handleExport" class="export-btn">
                导出
            </el-button>
        </div>

        <!-- 数据列表区域 -->
        <div class="table-section">
            <div class="table-header">
                <span class="table-title">数据列表</span>
            </div>
            <el-table 
                :data="tableData" 
                border 
                class="custom-table"
                style="width: 100%"
            >
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="product_Number" label="货品编号" width="120" />
                <el-table-column prop="product_Name" label="货品名称" width="150" />
                <el-table-column prop="specifications" label="规格型号" width="100" />
                <el-table-column prop="unit_Name" label="单位" width="60" align="center" />
                <el-table-column prop="category_Name" label="货品类型" width="100" />
                <el-table-column prop="warehouse_InOrOutCount" label="当前库存" width="80" align="center">
                    <template #default="scope">
                        <span class="inventory-count">{{ scope.row.warehouse_InOrOutCount }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="lower_limit" label="库存下限" width="80" align="center">
                    <template #default="scope">
                        <span class="limit-value lower">{{ scope.row.lower_limit }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="upper_limit" label="库存上限" width="80" align="center">
                    <template #default="scope">
                        <span class="limit-value upper">{{ scope.row.upper_limit }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="低于下限" width="80" align="center">
                    <template #default="scope">
                        <span class="warning-text">{{ getBelowLowerPercentage(scope.row) }}%</span>
                    </template>
                </el-table-column>
                <el-table-column label="高于上限" width="80" align="center">
                    <template #default="scope">
                        <span class="warning-text">{{ getAboveUpperPercentage(scope.row) }}%</span>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-section">
            <el-pagination v-model:current-page="data.PageIndex" v-model:page-size="data.PageSize"
                :page-sizes="[15, 20, 25, 30]" :background="true" layout="total, sizes, prev, pager, next, jumper"
                :total="data.Count" next-text="下一页" prev-text="上一页" class="custom-pagination" />
        </div>
    </div>
</template>

<script lang="ts" setup>
import { StorageRed } from '@/http/axiosHelper'
import { ElMessage } from 'element-plus'
import { onMounted, ref, watch } from 'vue'
// import { StorageRed } from '@/http/axiosHelper'

const tableData = ref([])

const data = ref({
    PageIndex: 1,
    PageSize: 15,
    Name: '',
    Type: '',
    UpUnder: '',
    Up: "",
    Under: "",
    Count: 0
})

const GetInventory = () => {
    StorageRed.get("/api/WorkOrder/InventoryAlert", {
        params: {
            PageIndex: data.value.PageIndex,
            PageSize: data.value.PageSize,
            Name: data.value.Name,
            Type: data.value.Type,
            UpUnder: data.value.UpUnder,
            Up: data.value.Up,
            Under: data.value.Under,
        }
    })
        .then((res:any) => {
            tableData.value = res.data.pageDatas;
            data.value.Count = res.data.totalCount
        })
}

// 产品类型树形列表
const categoryTreeList: any = ref([]);
// 获取产品类型树形结构
const getCategoryTreeList = () => {
  StorageRed({
    url: "/api/WorkOrder/GetProductCategoryTree",
    method: "get",
  }).then((res) => {
    categoryTreeList.value = res.data.data;
  });
};

// 重置表单
const resetForm = () => {
    data.value.Name = ''
    data.value.Type = ''
    data.value.UpUnder = ''
    data.value.Up = ''
    data.value.Under = ''
    data.value.PageIndex = 1
    GetInventory()
}

// 计算低于下限百分比
const getBelowLowerPercentage = (row: any) => {
    const current = row.warehouse_InOrOutCount
    const lower = row.lower_limit
    if (current < lower) {
        return ((lower - current) / lower * 100).toFixed(2)
    }
    return '0.00'
}

// 计算高于上限百分比
const getAboveUpperPercentage = (row: any) => {
    const current = row.warehouse_InOrOutCount
    const upper = row.upper_limit
    if (current > upper) {
        return ((current - upper) / upper * 100).toFixed(2)
    }
    return '0.00'
}

// 导出函数
async function handleExport() {
    try {
        const response = await StorageRed({
            url: '/api/WorkOrder/GetInventoryAlertExport', // 修改为正确的库存预警导出接口
            method: 'GET',
            params: {
                PageIndex: data.value.PageIndex,
                PageSize: data.value.PageSize,
                Name: data.value.Name,
                Type: data.value.Type,
                UpUnder: data.value.UpUnder,
                Up: data.value.Up,
                Under: data.value.Under,
            },
            responseType: 'blob',
        });

        // 从响应头获取文件名
        const fileName = getFileNameFromHeaders(response.headers);

        // 生成下载链接并触发下载
        const blob = new Blob([response.data], {
            type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();

        // 清理资源
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);

        ElMessage.success('库存预警数据导出成功')

    } catch (error: any) {
        console.error('导出失败：', error.response?.data || error.message);
        ElMessage.error('导出失败，请检查参数或重新登录');
    }
}

// 辅助函数：从响应头提取文件名
function getFileNameFromHeaders(headers: any) {
    const contentDisposition = headers['content-disposition'] || headers['Content-Disposition'];
    if (!contentDisposition) return '库存预警.xlsx';

    // 尝试从 Content-Disposition 中提取文件名
    const match = contentDisposition.match(/filename\*?=([^;]+)/);
    if (match) {
        return decodeURIComponent(match[1].replace(/["']/g, ''));
    }

    // 如果没有找到文件名，使用默认名称
    return '库存预警.xlsx';
}

watch(() => { data.value.PageIndex, data.value.PageSize }, () => {
    GetInventory();
}, { deep: true })

onMounted(() => {
    GetInventory();
    getCategoryTreeList();
})

</script>

<style scoped>
.inventory-alert-container {
    padding: 10px; /* 减少内边距 */
    background: #f5f5f5;
    min-height: 100vh;
    max-width: 1600px; /* 增加最大宽度 */
    margin: 0 auto; /* 居中显示 */
}

/* 搜索区域 */
.search-section {
    background: white;
    padding: 15px; /* 减少内边距 */
    margin-bottom: 15px; /* 减少底部间距 */
    border-radius: 4px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    width: 100%; /* 确保占满容器宽度 */
}

.section-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin: 0 0 12px 0; /* 减少底部间距 */
}

.search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 15px; /* 减少间距 */
    align-items: flex-end;
}

.form-item {
    margin-bottom: 0;
    min-width: 180px; /* 减少最小宽度 */
}

.custom-input,
.custom-select {
    border-radius: 4px;
    min-width: 130px; /* 减少最小宽度 */
}

.range-inputs {
    display: flex;
    align-items: center;
    gap: 8px;
}

.range-separator {
    color: #666;
    font-weight: 500;
}

.range-input {
    width: 120px; /* 减少输入框宽度 */
}

.button-group {
    display: flex;
    gap: 10px; /* 减少按钮间距 */
}

.reset-btn {
    background: #f5f5f5;
    border: 1px solid #ddd;
    color: #666;
}

.search-btn {
    background: #67c23a;
    border-color: #67c23a;
}

/* 操作按钮区域 */
.action-section {
    display: flex;
    justify-content: flex-end;
    gap: 10px; /* 减少按钮间距 */
    margin-bottom: 15px; /* 减少底部间距 */
}

.refresh-btn {
    background: #f5f5f5;
    border: 1px solid #ddd;
    color: #666;
}

.export-btn {
    background: #409eff;
    border-color: #409eff;
}

/* 表格区域 */
.table-section {
    background: white;
    border-radius: 4px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    margin-bottom: 15px; /* 减少底部间距 */
    width: 100%; /* 确保占满容器宽度 */
}

.table-header {
    padding: 12px 15px; /* 减少内边距 */
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.table-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

/* 表格样式优化 */
.custom-table {
    border-radius: 0;
    width: 100%; /* 确保表格占满容器宽度 */
    font-size: 13px; /* 稍微减小字体大小 */
}

.custom-table :deep(.el-table__header) {
    background: #f8f9fa;
}

.custom-table :deep(.el-table__header th) {
    background: #f8f9fa;
    color: #495057;
    font-weight: 600;
    border-bottom: 1px solid #dee2e6;
    font-size: 13px; /* 表头字体大小 */
    padding: 8px 4px; /* 减少表头内边距 */
}

.custom-table :deep(.el-table__row) {
    transition: background-color 0.3s ease;
}

.custom-table :deep(.el-table__row:hover) {
    background-color: #f8f9fa;
}

.custom-table :deep(.el-table__cell) {
    padding: 6px 4px; /* 减少单元格内边距 */
    font-size: 13px; /* 单元格字体大小 */
}

/* 表格数据样式 */
.inventory-count {
    font-weight: 600;
    color: #2c3e50;
    font-size: 12px; /* 减小字体大小 */
}

.limit-value {
    font-weight: 600;
    padding: 2px 4px; /* 减少内边距 */
    border-radius: 3px;
    font-size: 11px; /* 减小字体大小 */
}

.limit-value.lower {
    background: #f8d7da;
    color: #721c24;
}

.limit-value.upper {
    background: #d1ecf1;
    color: #0c5460;
}

.warning-text {
    color: #dc3545;
    font-weight: 600;
    font-size: 12px; /* 减小字体大小 */
}

/* 分页区域 */
.pagination-section {
    background: white;
    padding: 15px; /* 减少内边距 */
    border-radius: 4px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    text-align: center;
    width: 100%; /* 确保占满容器宽度 */
}

.custom-pagination :deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
    background: #67c23a;
    color: white;
}

.custom-pagination :deep(.el-pagination.is-background .el-pager li:not(.is-disabled):hover) {
    color: #67c23a;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .inventory-alert-container {
        padding: 8px; /* 移动端进一步减少内边距 */
        max-width: 100%; /* 移动端占满宽度 */
    }
    
    .search-form {
        flex-direction: column;
        align-items: stretch;
    }
    
    .form-item {
        margin-bottom: 16px;
        min-width: auto; /* 移动端取消最小宽度限制 */
    }
    
    .range-inputs {
        flex-direction: column;
        gap: 8px;
    }
    
    .range-input {
        width: 100%;
    }
    
    .action-section {
        flex-direction: column;
        align-items: stretch;
    }
}
</style>